package com.panshi.config;

import com.panshi.service.IAdminLoginService;
import com.panshi.tools.AdminLogin;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// 自定义 MyRealm
@Slf4j
public class AdminLoginRealm extends AuthorizingRealm {

    @Autowired
    public IAdminLoginService iAdminLoginService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 拿到下面方法返回值第一个的user对象
        AdminLogin adminLogin = (AdminLogin) subject.getPrincipal();

        // 设置当前用户的权限
       log.error("{}",adminLogin);
//        info.addStringPermission(user.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 用户名 密码    数据库查
//        String name ="admin";
//        String password="666";
        // 通过 authenticationToken 强转 获得当前用户的信息
        UsernamePasswordToken userTolen =  (UsernamePasswordToken)authenticationToken;
        // 判断当前用户是否存在数据库
//        if(!userTolen.getUsername().equals(name)){
//            // return null  自动抛出异常 UnknownAccountException  用户不存在
//            return null;
//        }

        AdminLogin adminLogin = iAdminLoginService.queryAdminByAdminName(userTolen.getUsername());


        if(adminLogin == null){
            return null;
        }
        // 判断密码认证 ， shiro自动做   加密了
        // 可以加密   MD5   MD5盐值加密
        return new SimpleAuthenticationInfo(adminLogin,adminLogin.getPassword(),"");
    }
}
